package com.yang.service;

import com.yang.entity.Category;
import com.yang.dao.CategoryDao;
import com.yang.pojo.ProductCategoryVO;
import com.yang.util.CategoryUtil;
import com.yang.util.RespEntity;
import  com.yang.pojo.categoryVO;

import java.util.*;

public class CategoryService {
    private final CategoryDao categoryDao = new CategoryDao();

    //查询全部
    public RespEntity queryCategory() {
        //得到全部的
        List<Category> categories = categoryDao.queryCategoryById(0);
        List<categoryVO> categoryVO = new ArrayList<>();
        for (Category category : categories) {
            List<Category> sons = categoryDao.queryCategoryById(category.getId());
            categoryVO categoryVO1 = new categoryVO(category.getId(),category.getName(),category.getParentid(),sons);
            categoryVO.add(categoryVO1);
        }
        return new RespEntity(200,"开始查询",categoryVO);
    }

    //单个查询
    public List<Category> queryCategoryById(Integer id) {
        return categoryDao.queryCategoryById(id);
    }

    //添加
    public RespEntity saveCategory(Category obj) {
        int sum = categoryDao.saveCategory(obj);
        return new RespEntity(200,"添加",sum);
    }
    //后台父类单个查询
    public RespEntity CategoryById(Integer id) {
        Category category = categoryDao.queryCategoryByIdHTML(id);
        return new RespEntity(200,"单个查询",category);
    }
/*    //后台子类单个查询
    public RespEntity queryById(int id) {
        //查询全部分类/父
        List<categoryVO> categoryVO = new ArrayList<>();
        List<Category> parent = categoryDao.queryCategoryById(0);
        //循环父查询全部子

            List<Category> sons = categoryDao.queryCategoryById(parent.get(0).getId());
             System.out.println("儿子的全部"+sons);

        //创建一个map存
        Map map=new HashMap();
        map.put("parent",parent);
        map.put("sons",sons);
        return new RespEntity(200,"子类修改")
    }*/
    //删除
    public RespEntity deleteCategory(Integer id,Integer pid) {
        //查询他有没有子类
        List<Category> sons=categoryDao.queryByPid(id);
        if(sons.size()==0){
            //没有子类可以删除
            int num = categoryDao.deleteCategoryById(id);
            return new RespEntity(200,"删除",num);
        }else {
            //有子类无法删除
            return new RespEntity(500,"失败",null);
        }
    }

    //删除子类
    public RespEntity deleteSon(Integer id) {
        int sum = categoryDao.deleteCategoryById(id);
        return new RespEntity(200,"删除",sum);
    }
    public RespEntity ParentNameUpdate(Category category) {
        int sum = categoryDao.updateCategoryById(category);
        return new RespEntity(200,"修改",sum);
    }


    //商品分类的商品展示
    public RespEntity queryAllCategory() {
        CategoryUtil categoryUtil = new CategoryUtil();
        List<ProductCategoryVO> categoryList = categoryUtil.getCategoryList(categoryDao.queryCategory());
        return new RespEntity(200,"成功",categoryList);
    }
}
